package com.smh.demo1.a21;

import com.smh.demo1.a20.MyDateFormatter;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * @author shiminghui
 * @date 2025/5/1 18:54
 * @description: TODO
 */
@Configuration
public class WebConfig {

    @ControllerAdvice  //这里的advice 与Aop的代理没有关系,它只是取了其增强的含义
    public static class MyControllerAdvice {
        @InitBinder // 注解加载这里,他就是全局生效,每个控制器类都会生效
        public void initBinder(WebDataBinder binder) {
            binder.addCustomFormatter(new MyDateFormatter());
        }

        @ExceptionHandler(RuntimeException.class)
        public void handleException(RuntimeException e) {
            System.out.println("出现了错误" + e.getMessage());
        }
    }

    @Controller
    public static class Controller1 {
        @InitBinder // 仅对当前控制器类生效
        public void initBinder(WebDataBinder binder) {
            binder.addCustomFormatter(new MyDateFormatter());
        }

        public void test() {
            System.out.println("Controller1.test");
        }
    }

    @Controller
    public static class Controller2 {
        @InitBinder
        public void initBinder1(WebDataBinder binder) {
            binder.addCustomFormatter(new MyDateFormatter());
        }

        @InitBinder
        public void initBinder2(WebDataBinder binder) {
            binder.addCustomFormatter(new MyDateFormatter());
        }

        public void test() {
            System.out.println("Controller2.test");
        }
    }
}
